/*
 * Created by SharpDevelop.
 * User: Guy Fomi
 * Date: 2/6/2011
 * Time: 2:14 PM
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;
using System.Collections;
using System.Collections.Generic;
using HtmlAgilityPack;
using System.Web.Script.Serialization;
using FileSystemDatabase;

namespace TomatoSynchronizer.Store
{
	/// <summary>
	/// Description of CustomerGroupStore.
	/// </summary>
	public class CustomerGroupStore
	{
		private Site _site;
		private HtmlWeb _client;
		
		private JsonDatabase db;
		public void PersistItemCustomerGroups(List<Dictionary<string,object>> groups)
		{
			db.Write<List<Dictionary<string,object>>>(groups,_site.Name);
		}

		public void PersistCustomerGroup(Dictionary<string,object> group)
		{
			db.Write<Dictionary<string,object>>(group,group["customers_groups_id"].ToString());
		}
		
		public CustomerGroupStore(Site site,HtmlWeb client)
		{
			db = new JsonDatabase("sites/" + site.Name + "/CustomerGroup");
			_site = site;
			_client = client;
		}
		
		public List<Dictionary<string,object>> GetCustomerGroups()
		{
			List<Dictionary<string,object>> records = new List<Dictionary<string,object>>();
			
			HtmlDocument doc = _client.Load(_site.Url + "/admin/json.php?action=list_customers_groups&module=customers_groups");
			HtmlNode node = doc.DocumentNode.SelectSingleNode("/");
			
			JavaScriptSerializer serialiser = new JavaScriptSerializer();
			Dictionary<string,object> json = serialiser.Deserialize<Dictionary<string,object>>(node.InnerText);
			foreach(string key in json.Keys)
			{
				if(key == "records")
				{
					ArrayList recs = (ArrayList)json[key];
					for(int i = 0;i < recs.Count;i++)
					{
						Dictionary<string,object> record = (Dictionary<string,object>)recs[i];						
						records.Add(record);												
					}									
				}
			}			
			
			return records;
		}		
	}
}
